package com.example.qfsx.bean;

import static android.app.PendingIntent.getActivity;

import android.content.Context;
import android.content.SharedPreferences;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import com.example.qfsx.Login;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Type;
import java.util.List;

public class NetworkUtils {
    private static final String URL = "http://123.56.141.187:8001/cart/index"; // 替换成你的API URL
    private static OkHttpClient client = new OkHttpClient();

    public void fetchItems(final ItemFetchCallback callback,Context _this) {
        String str = SharedPreferencesUtil.getString(_this,"response",null);
        Gson gson = new Gson();
        LoginResType userInfo = gson.fromJson(str, LoginResType.class);
        System.out.println("qf123 token"+userInfo.getData().token);

        Request request = new Request.Builder() //getLoginResponseFromPreferences
                .url(URL)
                .addHeader("authorization",userInfo.getData().token)
//                .addHeader("authorization","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjo2MzIsImlhdCI6MTczMDE4ODUxMX0.bEmiwGWBNozfWcSCtSNYG1t4z2mPFk6odjxHHDQ1KMs")
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful() && response.body() != null) {
                    String jsonData = response.body().string();
                    Gson gson = new Gson();
                    Type itemListType = new TypeToken<ResType2>() {}.getType();
                    ResType2 items = gson.fromJson(jsonData, itemListType);
                    callback.onSuccess(items.getData());
                } else {
                    callback.onFailure("zl Failed to fetch data");
                }
            }

            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("zl" +e.getMessage());
                callback.onFailure(e.getMessage());
            }
        });
    }


    public interface ItemFetchCallback {
        void onSuccess(List<CartItem2> items);
        void onFailure(String error);
    }
}